package com.soboot.tool.feign;

import com.soboot.base.constant.BaseConstant;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.util.Base64Utils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Author:
 * @createTime: 2022年09月20日 14:07:51
 * @version:
 * @Description:
 * @Copyright:
 */
@Configuration
public class FeignConfig {

    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        return requestTemplate -> {
            // 请求头中添加 Gateway Token
            String gatewayToken = new String(Base64Utils.encode(BaseConstant.Security.TOKENVALUE.getVal().getBytes()));
            requestTemplate.header(BaseConstant.Security.TOKENHEADER.getVal(), gatewayToken);
            // 请求头中添加原请求头中的 Token
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null) {
                Object details = authentication.getDetails();
                if (details instanceof OAuth2AuthenticationDetails) {
                    String authorizationToken = ((OAuth2AuthenticationDetails) details).getTokenValue();
                    requestTemplate.header(BaseConstant.Security.AUTHORIZATION.getVal(), BaseConstant.Security.TOKENTYPE.getVal() + authorizationToken);
                }
            }
        };
    }
}
